package com.chp.demo5.common.datasource;


import com.chp.demo5.business.entity.RzAcctDatabaseInfo;
import com.chp.demo5.business.mapper.RzAcctDatabaseInfoMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class LoadDataSourceRunner implements CommandLineRunner {

    @Resource
    private DynamicDataSource dynamicDataSource;
    @Resource
    private RzAcctDatabaseInfoMapper rzAcctDatabaseInfoMapper;

    @Override
    public void run(String... args) throws Exception {
//        DataSourceContextHolder.setDataSource("master");
        List<RzAcctDatabaseInfo> testDbInfos = rzAcctDatabaseInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(testDbInfos)) {
            List<DataSourceEntity> ds = new ArrayList<>();
            for (RzAcctDatabaseInfo testDbInfo : testDbInfos) {
                DataSourceEntity sourceEntity = new DataSourceEntity();
                BeanUtils.copyProperties(testDbInfo,sourceEntity);
                sourceEntity.setUserName(testDbInfo.getUsername());
                sourceEntity.setPassWord(testDbInfo.getPassword());
                sourceEntity.setDriverClassName("com.mysql.cj.jdbc.Driver");
                sourceEntity.setUrl(testDbInfo.getUrl());
                sourceEntity.setKey(testDbInfo.getDomain()+testDbInfo.getAcctId());
                ds.add(sourceEntity);
            }
            dynamicDataSource.createDataSource(ds);
        }
    }
}
